package com.example.EatOnTrojans;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.xml.sax.SAXException;


import com.example.EatOnTrojans.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;


import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class GoogleMapsActivity extends MapActivity {
    /** Called when the activity is first created. */
	
	LocationManager locationManager;
	MapView mapView;
	MapController mMapController;
	CurrentItemizedOverlay itemizedoverlayCurrent;
	HelloItemizedOverlay itemizedoverlayDine;
	private ImageButton mainButton;
	List<Overlay> mapOverlaysCurrent;
	List<Overlay> mapOverlays;
	
	private Spinner spinner1;
	private List<String> list = new ArrayList<String>(); 
	private ArrayAdapter<String> adapter;
	String filterText;
	private ProgressDialog progressDialog;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        
        /* set map control */
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);

        mapView.setTraffic(false);
        mapView.setSatellite(false);
        mMapController = mapView.getController();  
            
        mapOverlaysCurrent = mapView.getOverlays(); //set location overlay
        Drawable drawable1 = this.getResources().getDrawable(R.drawable.ic_launcher);
        itemizedoverlayCurrent = new CurrentItemizedOverlay(drawable1, this);
        float lat = 34.020668f;
        float lng = -118.289645f;
        GeoPoint point = new GeoPoint((int)(lat * 1E6), (int)(lng * 1E6));
        OverlayItem overlayitem = new OverlayItem(point, "Current Location", "Leavey");
        itemizedoverlayCurrent.addOverlay(overlayitem);
        mapOverlaysCurrent.add(itemizedoverlayCurrent);
        
        mMapController.animateTo(point);
        mMapController.setZoom(18);
        
        mainButton=(ImageButton)findViewById(R.id.imageButton1);
        mainButton.setOnClickListener(new ImageButton.OnClickListener(){
			@Override
			public void onClick(View v){
				Intent intent = new Intent();
				intent.setClass(GoogleMapsActivity.this, EatOnTrojansActivity.class);
				GoogleMapsActivity.this.startActivity(intent);
			}
		});
       
        spinner1 = (Spinner)findViewById(R.id.spinner1);
        //list of the spinner
        list.add("All restaurant");
        list.add("Within 0.5 miles");
        list.add("Cafe");
        list.add("Fast Food");
        list.add("Buffet");
        list.add("Snack Bar");

        //set adapter for the spinner
        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);    
        spinner1.setAdapter(adapter); 
        
        //set the spinner event when one item is chosen
        spinner1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){    
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id){    
            	filterText = adapter.getItem(position); 
            	try {
					showItem(position);

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }    
            public void onNothingSelected(AdapterView<?> parent) {}    
        }); 
       
    }
	
	public void showItem(int position) throws IOException, ParserConfigurationException, SAXException{
		
		
		//URL url=new URL("http://www-scf.usc.edu/~yunqingc/restaurant.xml"); 
        //URLConnection con=url.openConnection(); 
		//StringBuffer sb= StringBuffer();
		InputStream in = GoogleMapsActivity.class.getClassLoader().getResourceAsStream("restaurant.xml");
        if(in==null){
        	Toast.makeText(getApplicationContext(), "Cannot find data file",Toast.LENGTH_SHORT).show();
        }else{
	        DomXMLReader reader = new DomXMLReader();
	        ArrayList<RestRecord> restaurants = reader.readXML(in);
	        restaurants.get(0).image=R.drawable.rc_retail_tutor;
	        restaurants.get(1).image=R.drawable.irc;
	        restaurants.get(2).image=R.drawable.rc_retail_shop;
	        restaurants.get(3).image=R.drawable.rc_cc_panda;
	        restaurants.get(4).image=R.drawable.rc_cc_wahoos;
	        restaurants.get(5).image=R.drawable.rc_cc_carls;
	        restaurants.get(6).image=R.drawable.rc_cc_cpk;
	        restaurants.get(7).image=R.drawable.rc_cc_seeds;
	        restaurants.get(8).image=R.drawable.rc_retail_tgrounds;
	        restaurants.get(9).image=R.drawable.rc_retail_coffeebean;
	        restaurants.get(10).image=R.drawable.cafe84;
	        
        
			mapOverlays = mapView.getOverlays(); //set location overlay
	        
	        /* set item overlay */
	        Drawable drawable = this.getResources().getDrawable(R.drawable.pin);
	        itemizedoverlayDine = new HelloItemizedOverlay(drawable, this);
	        
	        for(RestRecord restaurant : restaurants){
	        	float lat1 = (float)restaurant.getLat();
	        	float lng1 = (float)restaurant.getLng();
	        	String restContent1=restaurant.getLocation()+";"+restaurant.getType()+";"+restaurant.getCuisine()+";"+restaurant.getHour()+";"+restaurant.getMenu()+";"+restaurant.getImage()+";"+restaurant.getRate()+";"+restaurant.getLat()+";"+restaurant.getLng();
	        	GeoPoint point1 = new GeoPoint((int)(lat1 * 1E6), (int)(lng1 * 1E6));
	        	OverlayItem overlayitem1 = new OverlayItem(point1, restaurant.getName(), restContent1);
	        	itemizedoverlayDine.addOverlay(overlayitem1);
	        } 
	        
	        mapOverlays.add(itemizedoverlayDine);
	        
        }

	}
	
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }

    private class HelloItemizedOverlay extends ItemizedOverlay{

    	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    	Context mContext;
    	private String restaurantConent[]=new String[10];
    	private String detial;
    	
    	public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
    		super(boundCenterBottom(defaultMarker));
    		mContext = context;
    		// TODO Auto-generated constructor stub
    	}
    	
    	public void addOverlay(OverlayItem overlay) {
    	    mOverlays.add(overlay);
    	    populate();
    	}
    	
    	public void addNewItem(GeoPoint location,String marketText,String snippet)
        {
    		mOverlays.add(new OverlayItem(location,marketText,snippet));
            populate();
        }
    	
    	public void removeItem(int index)
        {
    		mOverlays.remove(index);
            populate();

        }
    	
    	@Override
    	protected OverlayItem createItem(int i) {
    		return mOverlays.get(i);
    	}
    	
    	@Override
    	public int size() {
    		return mOverlays.size();
    	}
    	
    	@Override
    	protected boolean onTap(int index) {
    		OverlayItem item = mOverlays.get(index);
    		
    		final Dialog dialog = new Dialog(mContext);
    		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    		dialog.setContentView(R.layout.dialog);
    	
    		// set the custom dialog components - text, image and button
    		TextView textView1 = (TextView) dialog.findViewById(R.id.diagName);
    		TextView textView2 = (TextView) dialog.findViewById(R.id.diagLoc);
    		TextView textView5 = (TextView) dialog.findViewById(R.id.diagHour);
    		TextView textView3 = (TextView) dialog.findViewById(R.id.diagRev);
    		TextView textView4 = (TextView) dialog.findViewById(R.id.diagRate);
    		//TextView textView5 = (TextView) dialog.findViewById(R.id.textView5);
    		Button button1 = (Button) dialog.findViewById(R.id.diagBut);
    		button1.setText("Route");
    		detial=item.getTitle()+";"+item.getSnippet();
    		restaurantConent=item.getSnippet().split(";");
    		
    		textView1.setText(item.getTitle());
    		textView1.setPadding(10, 0, 20, 0);
    		String temp1="Location: "+restaurantConent[0];
    		textView2.setText(temp1);
    		textView2.setPadding(10, 0, 20, 0);
    		String temp3="Hour: "+restaurantConent[3];
    		textView5.setText(temp3);
    		textView5.setPadding(10, 0, 20, 0);
    		String temp2=restaurantConent[1]+": "+restaurantConent[2];
    		textView3.setText(temp2);
    		textView3.setPadding(10, 0, 20, 0);
    		textView4.setText("Menu: "+restaurantConent[4]);
    		textView4.setPadding(10, 0, 20, 0);
    		
    		RatingBar mRatingBar = (RatingBar) dialog.findViewById(R.id.diagStar);
    		mRatingBar.setNumStars(5);
    		mRatingBar.setRating(Float.parseFloat(restaurantConent[6]));
    		
    		ImageView image = (ImageView) dialog.findViewById(R.id.diagImg);
        	//Bitmap bm = getBitmap(restaurantConent[5]);
    		//image.setImageBitmap(bm);
    		int imageResource=Integer.parseInt(restaurantConent[5]);
    		image.setImageResource(imageResource);
    		
    		image.setMaxHeight(130);
    		image.setMaxWidth(130);
    		image.setPadding(10, 0, 20, 0);
    		
    		//display dialog
    		dialog.show();
    		dialog.setCanceledOnTouchOutside(true);
    		
    		ImageView cancel = (ImageView) dialog.findViewById(R.id.cancel);
    		cancel.setOnClickListener(new View.OnClickListener(){
	        	public void onClick(View v){
	        		dialog.dismiss();
	        	}
	        });
    		
    		button1.setOnClickListener(new View.OnClickListener() {
    			public void onClick(View v) {
    				progressDialog = new ProgressDialog(GoogleMapsActivity.this);
            		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            		progressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            		progressDialog.setMessage("Calculating...");
            		
            		progressDialog.show();  
    				Intent intent = new Intent();
        			intent.setClass(GoogleMapsActivity.this, RouteMapsActivity.class);
        			Bundle bundle = new Bundle();
        			bundle.putString("detial", detial);
        			intent.putExtras(bundle);
        			GoogleMapsActivity.this.startActivity(intent);
    			}
            });
    		
    		return true;
    	}
    	
    	
    	//get image from URL
    	public Bitmap getBitmap(String imageURL){ 
    		//initialize bitmap
    		Bitmap mBitmap = null; 
    		try { 
    			//open connection to the URL
    			URL url = new URL(imageURL); 
    			URLConnection conn = url.openConnection(); 
    			conn.connect();
    			InputStream is = conn.getInputStream(); 
    			BufferedInputStream buff = new BufferedInputStream(is);
    			//get image stream
    			mBitmap = BitmapFactory.decodeStream(buff); 
    			buff.close();
    			is.close();
    		} catch (MalformedURLException e) { 
    			e.printStackTrace(); 
    		} catch (IOException e) { 
    			e.printStackTrace(); 
    		} 
    		return mBitmap; 
    	} 
    }
    
    
    
    private class CurrentItemizedOverlay extends ItemizedOverlay{

    	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    	Context mContext;
    	private String restaurantConent[]=new String[10];
    	private String detial;
    	
    	public CurrentItemizedOverlay(Drawable defaultMarker, Context context) {
    		super(boundCenterBottom(defaultMarker));
    		mContext = context;
    		// TODO Auto-generated constructor stub
    	}
    	
    	public void addOverlay(OverlayItem overlay) {
    	    mOverlays.add(overlay);
    	    populate();
    	}
    	
    	public void addNewItem(GeoPoint location,String marketText,String snippet)
        {
    		mOverlays.add(new OverlayItem(location,marketText,snippet));
            populate();
        }
    	
    	public void removeItem(int index)
        {
    		mOverlays.remove(index);
            populate();

        }
    	
    	@Override
    	protected OverlayItem createItem(int i) {
    		return mOverlays.get(i);
    	}
    	
    	@Override
    	public int size() {
    		return mOverlays.size();
    	}
    	
    	@Override
    	protected boolean onTap(int index) {
    		OverlayItem item = mOverlays.get(index);
    		
    		Toast.makeText(getApplicationContext(), "Current Location: OHE",Toast.LENGTH_SHORT).show();
    		
    		return true;
    	}
    	
    	
    	
    }
    
}